//
//  ViewController.m
//  JxbLovelyLogin
//
//  Created by Peter on 15/8/11.
//  Copyright (c) 2015年 Peter. All rights reserved.
//

#import "ViewController.h"
#import "CCSecondViewController.h"
#import "CCRegisterViewController.h"
#define mainSize    [UIScreen mainScreen].bounds.size
#define offsetLeftHand      60
#define rectLeftHand        CGRectMake(61-offsetLeftHand, 90, 40, 65)
#define rectLeftHandGone    CGRectMake(mainSize.width / 2 - 100, vLogin.frame.origin.y - 22, 40, 40)
#define rectRightHand       CGRectMake(imgLogin.frame.size.width / 2 + 60, 90, 40, 65)
#define rectRightHandGone   CGRectMake(mainSize.width / 2 + 62, vLogin.frame.origin.y - 22, 40, 40)
@interface ViewController ()<UITextFieldDelegate>
{
    UITextField* txtUser;
    UITextField* txtPwd;
    UIImageView* imgLeftHand;
    UIImageView* imgRightHand;
    UIImageView* imgLeftHandGone;
    UIImageView* imgRightHandGone;
    JxbLoginShowType showType;
}
@end

@implementation ViewController

+ (NSString *)sharedName {
    static NSString *sharedName = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate,^{
        sharedName = [[self alloc] init];
    });
    return sharedName;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    UIImageView* imgLogin = [[UIImageView alloc] initWithFrame:CGRectMake(mainSize.width / 2 - 211 / 2, 100, 211, 109)];
    imgLogin.image = [UIImage imageNamed:@"owl-login"];
    imgLogin.layer.masksToBounds = YES;
    [self.view addSubview:imgLogin];
    
    imgLeftHand = [[UIImageView alloc] initWithFrame:rectLeftHand];
    imgLeftHand.image = [UIImage imageNamed:@"owl-login-arm-left"];
    [imgLogin addSubview:imgLeftHand];
    
    imgRightHand = [[UIImageView alloc] initWithFrame:rectRightHand];
    imgRightHand.image = [UIImage imageNamed:@"owl-login-arm-right"];
    [imgLogin addSubview:imgRightHand];

    UIView* vLogin = [[UIView alloc] initWithFrame:CGRectMake(15, 200, mainSize.width - 30, 160)];
    vLogin.layer.borderWidth = 0.5;
    vLogin.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    vLogin.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:vLogin];
    
    imgLeftHandGone = [[UIImageView alloc] initWithFrame:rectLeftHandGone];
    imgLeftHandGone.image = [UIImage imageNamed:@"icon_hand"];
    [self.view addSubview:imgLeftHandGone];
    
    imgRightHandGone = [[UIImageView alloc] initWithFrame:rectRightHandGone];
    imgRightHandGone.image = [UIImage imageNamed:@"icon_hand"];
    [self.view addSubview:imgRightHandGone];
    
    txtUser = [[UITextField alloc] initWithFrame:CGRectMake(30, 30, vLogin.frame.size.width - 60, 44)];
    txtUser.delegate = self;
    txtUser.layer.cornerRadius = 5;
    txtUser.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    txtUser.layer.borderWidth = 0.5;
    txtUser.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    txtUser.leftViewMode = UITextFieldViewModeAlways;
    UIImageView* imgUser = [[UIImageView alloc] initWithFrame:CGRectMake(11, 11, 22, 22)];
    imgUser.image = [UIImage imageNamed:@"iconfont-user"];
    [txtUser.leftView addSubview:imgUser];
    [vLogin addSubview:txtUser];
    
    txtPwd = [[UITextField alloc] initWithFrame:CGRectMake(30, 90, vLogin.frame.size.width - 60, 44)];
    txtPwd.delegate = self;
    txtPwd.layer.cornerRadius = 5;
    txtPwd.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    txtPwd.layer.borderWidth = 0.5;
    txtPwd.secureTextEntry = YES;
    txtPwd.leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 44, 44)];
    txtPwd.leftViewMode = UITextFieldViewModeAlways;
    UIImageView* imgPwd = [[UIImageView alloc] initWithFrame:CGRectMake(11, 11, 22, 22)];
    imgPwd.image = [UIImage imageNamed:@"iconfont-password"];
    [txtPwd.leftView addSubview:imgPwd];
    [vLogin addSubview:txtPwd];
    
    //登录按钮
    UIButton *loginBtn = [[UIButton alloc]initWithFrame:CGRectMake(vLogin.center.x - 40, vLogin.center.y + (vLogin.frame.size.height * 0.6) , 80, 40)];
    loginBtn.layer.cornerRadius = 5;
    loginBtn.layer.backgroundColor = [[UIColor colorWithRed:0.4 green:0.5 blue:0.2 alpha:1]CGColor];
    loginBtn.layer.borderWidth = 0.5;
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    [loginBtn setTitleColor:[UIColor colorWithRed:0.2 green:0.7 blue:0.9 alpha:1] forState:UIControlStateNormal];
    loginBtn.showsTouchWhenHighlighted = YES;
    [loginBtn addTarget:self action:@selector(loginBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:loginBtn];
    
    UIButton *registerBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 10, 60, 30)];
    registerBtn.layer.cornerRadius = 5;
    registerBtn.layer.backgroundColor = (__bridge CGColorRef _Nullable)([UIColor clearColor]);
    [registerBtn setTitle:@"注册" forState:UIControlStateNormal];
    [registerBtn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [registerBtn addTarget:self action:@selector(registerBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:registerBtn];
}

- (void)registerBtnClick {
    UIStoryboard *myStoryboard=[UIStoryboard storyboardWithName:@"Register" bundle:nil];
    CCRegisterViewController *registerController=[myStoryboard instantiateViewControllerWithIdentifier:@"Register"];
    [self presentViewController:registerController animated:YES completion:nil];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [txtUser resignFirstResponder];
    [txtPwd resignFirstResponder];
}

- (void)textFieldDidBeginEditing:(UITextField *)textField {
    if ([textField isEqual:txtUser]) {
        if (showType != JxbLoginShowType_PASS)
        {
            showType = JxbLoginShowType_USER;
            return;
        }
        showType = JxbLoginShowType_USER;
        [UIView animateWithDuration:0.5 animations:^{
            imgLeftHand.frame = CGRectMake(imgLeftHand.frame.origin.x - offsetLeftHand, imgLeftHand.frame.origin.y + 30, imgLeftHand.frame.size.width, imgLeftHand.frame.size.height);
            imgRightHand.frame = CGRectMake(imgRightHand.frame.origin.x + 48, imgRightHand.frame.origin.y + 30, imgRightHand.frame.size.width, imgRightHand.frame.size.height);
            imgLeftHandGone.frame = CGRectMake(imgLeftHandGone.frame.origin.x - 70, imgLeftHandGone.frame.origin.y, 40, 40);
            imgRightHandGone.frame = CGRectMake(imgRightHandGone.frame.origin.x + 30, imgRightHandGone.frame.origin.y, 40, 40);
        } completion:^(BOOL b) {
        }];
    }
    else if ([textField isEqual:txtPwd]) {
        if (showType == JxbLoginShowType_PASS)
        {
            showType = JxbLoginShowType_PASS;
            return;
        }
        showType = JxbLoginShowType_PASS;
        [UIView animateWithDuration:0.5 animations:^{
            imgLeftHand.frame = CGRectMake(imgLeftHand.frame.origin.x + offsetLeftHand, imgLeftHand.frame.origin.y - 30, imgLeftHand.frame.size.width, imgLeftHand.frame.size.height);
            imgRightHand.frame = CGRectMake(imgRightHand.frame.origin.x - 48, imgRightHand.frame.origin.y - 30, imgRightHand.frame.size.width, imgRightHand.frame.size.height);
            imgLeftHandGone.frame = CGRectMake(imgLeftHandGone.frame.origin.x + 70, imgLeftHandGone.frame.origin.y, 0, 0);
            imgRightHandGone.frame = CGRectMake(imgRightHandGone.frame.origin.x - 30, imgRightHandGone.frame.origin.y, 0, 0);
        } completion:^(BOOL b) {
        }];
    }
}

- (void)loginBtnClick {
    //http://localhost:8888/test/login.php?username=admin1&password=12345
    __block UIAlertView *alertView=nil;
    NSString *urlStr=[NSString stringWithFormat:@"http://127.0.0.1:8888/php/ycuserdb/login.php?name=%@&password=%@",txtUser.text,txtPwd.text];
    NSLog(@"%@",urlStr);
    NSURL *url=[NSURL URLWithString:[urlStr stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
    NSURLRequest *request=[[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
    [NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc]init] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        NSDictionary *dic=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        [[NSOperationQueue mainQueue] addOperationWithBlock:^{
            if ([dic[@"code"] intValue]==0) {//登陆成功
                NSLog(@"0");
                alertView=[[UIAlertView alloc]initWithTitle:@"登陆提醒" message:@"登陆成功" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alertView show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alertView dismissWithClickedButtonIndex:1 animated:YES];
                    UIStoryboard *myStoryboard=self.storyboard;
                    CCSecondViewController *secondController=[myStoryboard instantiateViewControllerWithIdentifier:@"SecondStoryboard"];
                    secondController.username=dic[@"data"][@"name"];
                    secondController.userpassword=dic[@"data"][@"password"];
                    [self presentViewController:secondController animated:YES completion:nil];
                });
            }
            else if([dic[@"code"] intValue]==1){//用户名不存在
                NSLog(@"1");
                alertView=[[UIAlertView alloc]initWithTitle:@"登陆提醒" message:@"用户名不存在,是否注册?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"注册", nil];
                [alertView show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    txtUser.text=@"";
                    txtPwd.text=@"";
                    [alertView dismissWithClickedButtonIndex:1 animated:YES];
                });
            }
            else {//用户名或者密码错误
                NSLog(@"3");
                alertView=[[UIAlertView alloc]initWithTitle:@"登陆提醒" message:@"用户名或者密码错误！" delegate:nil cancelButtonTitle:nil otherButtonTitles:nil, nil];
                [alertView show];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [alertView dismissWithClickedButtonIndex:1 animated:YES];
                });
            }
            [self.view endEditing:YES];
        }];
    }];
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex==1) {
        UIStoryboard *myStoryboard=[UIStoryboard storyboardWithName:@"Register" bundle:nil];
        CCRegisterViewController *registerController=[myStoryboard instantiateViewControllerWithIdentifier:@"Register"];
        [self presentViewController:registerController animated:YES completion:nil];
    }
}
- (void)viewWillAppear:(BOOL)animated{
    txtPwd.text=@"";
}

@end
